package cn.e3mall.sso.service.impl;

import java.util.Date;
import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import cn.e3mall.common.util.E3Result;
import cn.e3mall.mapper.TbUserMapper;
import cn.e3mall.pojo.TbUser;
import cn.e3mall.pojo.TbUserExample;
import cn.e3mall.pojo.TbUserExample.Criteria;
import cn.e3mall.sso.service.RegisterService;

@Service
public class RegisterServiceImpl implements RegisterService {

	@Autowired
	private TbUserMapper tbUserMapper;

	@Override
	public E3Result checkData(String param, int type) {
		// 首先根据不同的type生成不同的查询条件
		TbUserExample example = new TbUserExample();
		Criteria criteria = example.createCriteria();
		// 1是用户名，2是手机号 3是邮箱
		if (type == 1) {
			criteria.andUsernameEqualTo(param);
		} else if (type == 2) {
			criteria.andPhoneEqualTo(param);
		} else if (type == 3) {
			criteria.andEmailEqualTo(param);
		} else {
			return E3Result.build(400, "数据类型错误");
		}
		// 执行查询
		List<TbUser> list = tbUserMapper.selectByExample(example);
		// 判断结果是否包涵数据
		if (list != null && list.size() > 0) {
			return E3Result.ok(false);
		}
		// 如果有数据返回false
		// 如果没有数据返回true
		return E3Result.ok(true);
	}

	@Override
	public E3Result register(TbUser tbUser) {
		if (StringUtils.isBlank(tbUser.getUsername()) || StringUtils.isBlank(tbUser.getPhone()) 
				|| StringUtils.isBlank(tbUser.getPassword())) {
			return E3Result.build(400, "用户名数据不完整，注册失败");
		}
		E3Result result = checkData(tbUser.getUsername(), 1);
		if (!(boolean) result.getData()) {
			return E3Result.build(400, "用户名已被占用");
		}
		result = checkData(tbUser.getPhone(), 2);
		if (!(boolean) result.getData()) {
			return E3Result.build(400, "手机号已被占用");
		}
		tbUser.setCreated(new Date());
		tbUser.setUpdated(new Date());
		String md5Pass = DigestUtils.md5DigestAsHex(tbUser.getPassword().getBytes());
		tbUser.setPassword(md5Pass);
		tbUserMapper.insert(tbUser);
		return E3Result.ok();
	}

}
